package com.example.security.service;

import com.example.security.entity.Department;
import com.example.security.mapper.DepartmentMapper;
import com.example.security.model.Result;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class DepartmentService {

    private DepartmentMapper departmentMapper;

    public Result getAllDepartment() {
        // 查询所有的部门
        List<Department> departments = departmentMapper.selectList(null);

        /**
         * MultiValueMap 该类是spring提供的一个类，key就是map的key，value是一个 List
         * Map<Integer, List<Department>>
         *
         * 作用就是按照 parentId相同的部门把他们归为一类:
         *    18 - ['上海分公司', '北京分公司']
         *    17 -> ['北京分公司']
         *    22 -> ['技术部', '市场部']
         *    19 -> ['魏国', '蜀国', '吴国']
         */
        MultiValueMap<Integer, Department> parentIdToDepartment = new LinkedMultiValueMap<>();

        // 所有的顶级部门
        List<Department> rootDepartment = departments.stream().filter(department -> {
            Integer parentId = department.getParentId();

            if(null != parentId) {
                List<Department> depts = parentIdToDepartment.get(parentId);
                if(null == depts) {
                    depts = new ArrayList<>();
                    depts.add(department);
                    parentIdToDepartment.put(parentId, depts);
                }else {
                    depts.add(department);
                }
            }
            return parentId == null;
//            if(null == department.getParentId()) {
//                return true;
//            }
//            return false;
        }).collect(Collectors.toList());

        // sort() 就是原本的集合上进行排序的
        rootDepartment.sort((d1, d2) -> d1.getOrderNum() - d2.getOrderNum());

        generateDepartmentTree(rootDepartment, parentIdToDepartment);

        return Result.buildSuccess(rootDepartment);
    }

    // 递归方法构建 部门的 递归树
    public void generateDepartmentTree(List<Department> departments, MultiValueMap<Integer, Department> parentIdToDepartment) {
        departments.forEach(department -> {
            Integer id = department.getId(); // 获取部门id， 找子部门

            List<Department> children = parentIdToDepartment.get(id);  // 获取所有的子部门
            if(null != children && children.size() > 0) {
                children.sort((d1, d2) -> d1.getOrderNum() - d2.getOrderNum());  // 子部门要排序
                department.setChildren(children);
                // 给所有的子部门设置父部门，但是该代码有一定的问题
//                children.forEach(dept -> {
//                    dept.setParent(department);
//                });
                generateDepartmentTree(children, parentIdToDepartment);
            }
        });
    }
}
